import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/login'
import Home from '@/components/home'
import Welcome from '@/components/welcome'
Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/login'
  },

  // 普通路由
  {
    path: '/login',
    component: Login
  },
  // 嵌套路由
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [{
      path: '/welcome',
      component: Welcome
    }]
  }
]

const router = new VueRouter({
  routes
})

export default router

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to: 到跳转的页面；
  // from: 从那个页面跳转过来；
  // next: 放行函数

  // 如果访问的是登录页面直接放行
  if (to.path === '/login') {
    return next()
  } else {
    // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
    if (tokenStr) {
      return next()
    } else {
      return next('/login')
    }
  }
})
